<?php

class nl_dc {

    private $db;
    private $cache;
    private $config;
    private $cache_enabled;
    private $cache_opened = FALSE;
    private $db_opened = FALSE;

    private $redis_elements= array();
    private $redis_opened = array();
    static private $debuger;
//	当debug_rule为0，代表所有SQL信息都输出，当debug_rule为1，代表只输出错误SQL信息.
    static private $debug_rule = 1;
//	记录当前所创建的数据库IP地址
    static private $db_ip = NULL;
    static public $db_debug_enable = 0;
    static public $db_debug_arr = NULL;
	static public $obj_dc = null;
	
	/**
	 * @return the $db
	 */
	public function getDb()
	{
		return $this->db;
	}

	/**
	 * @param field_type $db
	 */
	public static function setDb($db)
	{
		nl_dc::$db = $db;
	}

	//	public function __construct($config,$params=null){
//		global $g_mem_cache_enabled;
//		$this->config = $config;
//		$this->db = nl_get_db($config['db_policy'],$params);
//		if ($g_mem_cache_enabled==0){
//
//			$this->cache_enabled=FALSE;
//			$this->cache = nl_get_cache(NP_KV_CACHE_TYPE_NULL,$params);
//		}else{
//
//			$this->cache_enabled=TRUE;
//			$this->cache = nl_get_cache($config['cache_policy'],$params);
//		}
//	}

	//czy 2014-7-6 不要在构造函数前填代码
    static public function db_ip($ip = NULL) {
        if (!empty($ip)) {
            self::$db_ip = $ip;
        } else {
            return self::$db_ip;
        }
    }

    public function __construct($config, $params = NULL, $platform = '') {
        global $g_mem_cache_enabled;
        $this->config = $config;
        if($platform === 'log_db')
        	$platform = 'log';
        
        $platform_str = empty($platform)?"":"_{$platform}";
//        switch ($platform) {
//            case 'sub_platform':
//                $func_db = 'nl_get_sub_platform_db';
//                $func_cache = 'nl_get_sub_platform_cache';
//                $func_redis='nl_get_redis';
//                break;
//            case 'log_db':
//                $func_db = 'nl_get_log_db';
//                $func_cache = 'nl_get_cache';
//                $func_redis='nl_get_log_redis';
//                break;
//            case 'dy':
//                $func_db = 'nl_get_dy_db';
//                $func_cache = 'nl_get_dy_cache';
//                $func_redis='nl_get_log_redis';
//                break;
//            case 'pay':
//                $func_db = 'nl_get_pay_db';
//                $func_cache = 'nl_get_pay_cache';
//                $func_redis='nl_get_pay_redis';
//                break;
//			case 'aaa':
//				$func_db = 'nl_get_aaa_db';
//				$func_cache = 'nl_get_aaa_cache';
//				break;
//			case 'boss':
//				$func_db = 'nl_get_boss_db';
//				$func_cache = 'nl_get_boss_cache';
//				break;
//            default:
//                $func_db = 'nl_get_db';
//                $func_cache = 'nl_get_cache';
//                break;
//        }

        $func_db = "nl_get{$platform_str}_db";
        $func_cache = "nl_get{$platform_str}_cache";
//        $func_redis = "nl_get_redis_v2";

        if (!function_exists($func_cache)) $func_cache = "nl_get_cache";
//        if (!function_exists($func_redis)) $func_redis = "nl_get_redis_v2";

        if (function_exists($func_db) && function_exists($func_cache) ) {
            if (self::$db_debug_enable == 1) {

                $params['db_log'] = NP_DB_LOG_SQL_DEBUG_EXPLAIN;
            }
            
            $this->db = $func_db($config['db_policy'], $params);
            if (self::$db_debug_enable == 1) {
                if (!is_array(self::$db_debug_arr)) {
                    self::$db_debug_arr = array();
                }
                self::$db_debug_arr[] = $this->db;
            }

//            $config['redis_policy'] = strlen($config['redis_policy']) == 0?NL_REDIS_WRITE:$config['redis_policy'];
//            $this->redis = $func_redis($config['redis_policy'],$platform);

            if ($g_mem_cache_enabled == 0 || $platform == 'log') {

                $this->cache_enabled = FALSE;
                $this->cache = $func_cache(NP_KV_CACHE_TYPE_NULL, $params);
            } else {

                $this->cache_enabled = TRUE;
                $this->cache = $func_cache($config['cache_policy'], $params);
            }
        } else {
            
        }
        
       
//         self::$obj_dc = (isset($config['db_policy']) && strlen($config['db_policy']) > 0 && in_array('1', explode('|', $config['db_policy']))) ? $this : null;
    }

    public function __destruct() {
//         $this->close();
    }

    /**
     * 获取DB策略
     * @return String DB策略 NL_DB_WRITE | NL_DB_READ
     */
    public function get_db_policy() {
        return $this->config['db_policy'];
    }

    /**
     * 获取CACHE策略
     * @return String CACHE策略 NP_KV_CACHE_TYPE_NULL | NP_KV_CACHE_TYPE_MEMCACHE | NP_KV_CACHE_TYPE_MEMCACHED
     */
    public function get_cache_policy() {
        return $this->config['cache_policy'];
    }


    /**
     * 获取DB模块
     * @return db模块
     */
    public function db() {
        $this->open_db();
        return $this->db;
    }

    /**
     * 获取Redis模块
     * @param NL_REDIS_WRITE|NL_REDIS_READ
     * @return redis模块
     */
    public function epg_redis($policy) {
        if (!isset($this->redis_elements["epg"]))
        {
            $this->redis_elements["epg"] = nl_get_redis_v2($policy,"epg");
        }
        $this->open_redis("epg");
        return $this->redis_elements["epg"];
    }

    /**
     * 获取user Redis模块
     * @param NL_REDIS_WRITE|NL_REDIS_READ
     * @return user-redis模块
     */
    public function user_redis($policy) {
        if (!isset($this->redis_elements["user"]))
        {
            $this->redis_elements["user"] = nl_get_redis_v2($policy,"user");
        }
        $this->open_redis("user");
        return $this->redis_elements["user"];
    }

    /**
     * 获取微信Redis模块
     * @param NL_REDIS_WRITE|NL_REDIS_READ
     * @return 微信redis模块
     */
    public function wx_redis($policy) {
        if (!isset($this->redis_elements["wx"]))
        {
            $this->redis_elements["wx"] = nl_get_redis_v2($policy,"wx");
        }
        $this->open_redis("wx");
        return $this->redis_elements["wx"];
    }

    /**
     * 获取Redis模块
     * @param NL_REDIS_WRITE|NL_REDIS_READ
     * @return redis模块
     */
    public function aaa_redis($policy) {
        if (!isset($this->redis_elements["aaa"]))
        {
            $this->redis_elements["aaa"] = nl_get_redis_v2($policy,"aaa");
        }
        $this->open_redis("aaa");
        return $this->redis_elements["aaa"];
    }

    /**
     * 获取CACHE模块
     * @return CACHE模块
     */
    public function cache() {
        $this->open_cache();
        return $this->cache;
    }

    /**
     * 是否开启CACHE
     * @return TRUE 
     * 			FALSE
     */
    public function is_cache_enabled() {
        return $this->cache_enabled;
    }

    /**
     * 打开DC
     * 如果CACHE功能未开启，只打开DB模块
     * 如果CACHE功能开启，同时打开CACHE和DB模块  返回结果仅以DB是否成功开启为准
     * @return TRUE 成功
     * 			FALSE 失败
     */
    public function open() {
        if (isset($this->config['delay_open_cache']) && $this->config['delay_open_cache'] === true) {
            
        } else {
            $this->open_cache();
        }
        if (isset($this->config['delay_open_db']) && $this->config['delay_open_db'] === true) {
            return TRUE;
        }

//		return $this->db->open() && $cache_opened ;

        return $this->open_db();
    }

    public function open_cache() {
        if ($this->cache_enabled) {
            if ($this->cache_opened === FALSE)
                $this->cache_opened = $this->cache->open();
        }

        return $this->cache_opened;
    }

    public function open_db() {

        if (!$this->db_opened && is_object($this->db))
            $this->db_opened = $this->db->open();
        return $this->db_opened;
    }

    private function open_redis($type) {

        if (!$this->redis_opened[$type] && is_object($this->redis_elements[$type]))
            $this->redis_opened[$type] = $this->redis_elements[$type]->open();
        return $this->redis_opened[$type];
    }

    public function is_db_open() {
        return $this->db_opened;
    }

    public function is_redis_open() {
        return $this->redis_opened;
    }

    public function is_cache_open() {
        return $this->cache_opened;
    }

    /**
     * 关闭DC
     * 如果CACHE功能未开启，只关闭DB模块
     * 如果CACHE功能开启，同时关闭CACHE和DB模块 返回结果仅以DB是否成功关闭为准
     * @return TRUE 成功
     * 			FALSE 失败
     */
    public function close() {
        $cache_closed = TRUE;
        if ($this->cache_enabled) {
//			if ($this->cache===NULL){
//				return FALSE;
//			}			
            $cache_closed = $this->cache->close();
        }
//		return $this->db->close() && $cache_closed;
        if (is_object($this->db))
            return $this->db->close();
        return null;
    }

    /**
     * 抛出DEBUGER信息
     * @param DEBUGER信息
	 * czy 2014-7-6 后面删除吧，这个没啥用。要调试也不是这么记的。
	 * 命名也不要这样写，我们并没有用异常机制，不要写这种命名出来，这个最多就是一个 push_debug_info
     */
    static public function throw_debug($sql, $reason, $debug_code = NULL) {
        if (!isset(self::$debuger) || empty(self::$debuger)) {
            self::$debuger = array();
        }

        if ($debug_code === NULL) {
            $debug_code = 0;
//			若没有错误码，代表非错误信息
            if (self::$debug_rule == 1) {
                return;
            }
        }

        $debug_info = array();

        $debug_info['code'] = $debug_code;
        $debug_info['sql'] = $sql;
        $debug_info['reason'] = $reason;

        array_push(self::$debuger, $debug_info);
    }

    /**
     * 获取错误
     * @param format格式化类型
     *    A 为数组
     * 	  T 为文本
     * @return array()
     */
    static public function last_debug($format = 'A') {
        if ($format === 'A') {
            return self::$debuger;
        } elseif ($format === 'T') {
            $output = '';
            //LMS 兼容 2014 -7-3
            $list_debug = is_array(self::$debuger) ? self::$debuger : array();
            foreach ($list_debug as $debug) {
                $output .= $debug['code'] . "			" . $debug['reason'] . "		" . $debug['sql'] . "\n";
            }
            return $output;
        } else {
            return self::$debuger;
        }
    }

}

?>
